//
//  MarketViewModel.swift
//  Exchange
//
//  Created by rui on 2018/7/3.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class MarketViewModel: BaseViewModel {
    
    ///轮播图url
    var banners: [BannerInfo] = []
    
    private lazy var bannerApi: HomeBannerRequest = {
        let api = HomeBannerRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    ///加载轮播图
    func loadBannerInfo()  {
        self.bannerApi.loadData()
    }
}

extension MarketViewModel: RequestCallBack,RequestDataReformer,RequestParamSource {
    
    func reform(_ request: BaseRequest, _ data: [String : Any]?) {
        if let _ = request as? HomeBannerRequest {
            var flag = false
            if let list = data?["data"] as? [[String:Any]] {
                if let jsonData = list.jsonData {
                    do{
                        let list = try JSONDecoder().decode(Array<BannerInfo>.self, from: jsonData)
                        self.banners.removeAll()
                        self.banners.append(contentsOf: list)
                        flag = true
                    }catch {
                        flag = false
                        dPrint(error)
                    }
                }
            }
            self.response?(ResponseState.home_banner_info,flag, nil)
        }
    }
    
    func requestDidSucess(_ request: BaseRequest) {
        
    }
    
    func requestDidFail(_ request: BaseRequest) {
        if let _ = request as? HomeBannerRequest {
            self.response?(ResponseState.home_banner_info,false, nil)
        }
    }
    
    func requestParams(_ request: BaseRequest) -> [String : Any]? {
        var pramas: [String:Any] = [:]
        if let _ = request as? HomeBannerRequest {
          /// type = 1 app  = 2 pc
           pramas.updateValue(1, forKey: "type")
        }
        return pramas
    }
    
}
